<template>
  <div class="project-edit-container">
    <el-page-header @back="goBack" :content="pageTitle" />
    
    <el-card class="edit-form-card" v-loading="loading">
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="rules" 
        label-width="120px"
        label-position="top"
      >
        <!-- 基础信息部分 -->
        <el-divider content-position="left">基础信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName" required>
              <el-input 
                v-model="formData.projectName" 
                placeholder="请输入项目名称" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectCode" required>
              <el-input 
                v-model="formData.projectCode" 
                placeholder="请输入项目编号" 
                :disabled="isEditMode"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产业类别" prop="industryCategory" required>
              <el-select
                v-model="formData.industryCategory"
                placeholder="请选择产业类别"
                class="full-width"
                clearable
              >
                <el-option
                  v-for="item in industryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目状态" prop="status" required>
              <el-select
                v-model="formData.status"
                placeholder="请选择项目状态"
                class="full-width"
                clearable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属园区" prop="parkName">
              <el-input 
                v-model="formData.parkName" 
                placeholder="请输入所属园区" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目阶段" prop="state" required>
              <el-select 
                v-model="formData.state" 
                class="full-width"
                clearable
              >
                <el-option label="在谈" value="inTalk" />
                <el-option label="征地报批" value="landApproval" />
                <el-option label="建设中" value="construction" />
                <el-option label="竣工验收" value="completion" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 投资信息部分 -->
        <el-divider content-position="left">投资信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="投资方" prop="investor" required>
              <el-input 
                v-model="formData.investor" 
                placeholder="请输入投资方" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划总投资(万元)" prop="totalInvestment" required>
              <el-input-number 
                v-model="formData.totalInvestment" 
                :min="0" 
                :precision="2" 
                class="full-width"
                :controls="false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="固定资产总投资(万元)" prop="fixedAssetsInvestment">
              <el-input-number 
                v-model="formData.fixedAssetsInvestment" 
                :min="0" 
                :precision="2" 
                class="full-width"
                :controls="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用地面积(亩)" prop="landArea">
              <el-input-number 
                v-model="formData.landArea" 
                :min="0" 
                :precision="2" 
                class="full-width"
                :controls="false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 项目信息部分 -->
        <el-divider content-position="left">项目信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="年产值(万元)" prop="outputValue">
              <el-input-number 
                v-model="formData.outputValue" 
                :min="0" 
                :precision="2" 
                class="full-width"
                :controls="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年纳税(万元)" prop="taxRevenue">
              <el-input-number 
                v-model="formData.taxRevenue" 
                :min="0" 
                :precision="2" 
                class="full-width"
                :controls="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目类型" prop="projectType" required>
              <el-select 
                v-model="formData.projectType" 
                class="full-width"
                clearable
              >
                <el-option label="独立选址" value="independent" />
                <el-option label="租赁厂房" value="rental" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目来源" prop="projectSource">
      <el-select v-model="formData.projectSource" class="full-width">
        <el-option label="自有线索" value="自有线索" />
        <el-option label="中介介绍" value="中介介绍" />
        <el-option label="展会获取" value="展会获取" />
      </el-select>
    </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目周期(月)" prop="projectDuration">
              <el-input-number 
                v-model="formData.projectDuration" 
                :min="1" 
                :max="120" 
                class="full-width"
                :controls="false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选址地址" prop="selectedAddress">
              <el-input 
                v-model="formData.selectedAddress" 
                placeholder="请输入选址地址" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始施工日期" prop="constructionStartDate">
              <el-date-picker
                v-model="formData.constructionStartDate"
                type="date"
                placeholder="选择开始施工日期"
                value-format="YYYY-MM-DD"
                class="full-width"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 投资方信息部分 -->
        <el-divider content-position="left">投资方信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input 
                v-model="formData.contactPerson" 
                placeholder="请输入联系人" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input 
                v-model="formData.contactPhone" 
                placeholder="请输入联系电话" 
                clearable
                maxlength="11"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系地址" prop="address">
              <el-input 
                v-model="formData.address" 
                placeholder="请输入联系地址" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跟进人" prop="follower">
              <el-input 
                v-model="formData.follower" 
                placeholder="请输入跟进人" 
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="企业简介" prop="investorDescription">
          <el-input
            v-model="formData.investorDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入企业简介"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 项目详情部分 -->
        <el-form-item label="项目简介" prop="description" required>
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入项目简介"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 合同信息部分 -->
        <el-divider content-position="left">合同信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractCode">
              <el-input 
                v-model="formData.contractCode" 
                placeholder="请输入合同编号" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="contractType">
              <el-input 
                v-model="formData.contractType" 
                placeholder="请输入合同类型" 
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="签约日期" prop="signDate">
              <el-date-picker
                v-model="formData.signDate"
                type="date"
                placeholder="选择签约日期"
                value-format="YYYY-MM-DD"
                class="full-width"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同金额(万元)" prop="contractAmount">
              <el-input-number 
                v-model="formData.contractAmount" 
                :min="0" 
                :precision="2" 
                class="full-width"
                :controls="false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="合同主要内容" prop="contractContent">
          <el-input
            v-model="formData.contractContent"
            type="textarea"
            :rows="3"
            placeholder="请输入合同主要内容"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="loading"
          >
            {{ loading ? '提交中...' : '保存修改' }}
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})

// 计算属性
const isEditMode = computed(() => {
  console.log('路由参数:', route.params)
  console.log('查询参数:', route.query)
  return route.query.id ? true : false  // 使用 query.id
})

const pageTitle = computed(() => {
  return isEditMode.value ? '编辑项目' : '新增项目'
})

const projectId = computed(() => {
  return route.query.id 
})

// 完整的表单数据
const formData = ref({
  projectName: '',
  projectCode: '',
  investor: '',
  address: '',
  contactPerson: '',
  contactPhone: '',
  industryCategory: '',
  parkName: '',
  status: '在谈',
  state: 'inTalk',
  projectType: 'independent',
  description: '',
  investorDescription: '',
  projectDuration: 12,
  constructionStartDate: '',
  totalInvestment: 0,
  fixedAssetsInvestment: 0,
  landArea: 0,
  outputValue: 0,
  taxRevenue: 0,
  projectSource: '',
  selectedAddress: '',
  follower: '',
  contractCode: '',
  contractType: '',
  signDate: '',
  contractAmount: 0,
  contractContent: ''
})

// 获取项目详情
const fetchProjectDetail = async () => {
  if (!isEditMode.value) {
    console.log('不是编辑模式，跳过数据加载')
    return
  }
  
  if (!projectId.value) {
    ElMessage.error('项目ID不存在')
    return
  }

  try {
    loading.value = true
    console.log('开始加载项目数据，ID:', projectId.value)
    
    // 添加请求拦截器日志
    console.log('发送请求: GET', `/api/projects/${projectId.value}`)
    
    const response = await api.get(`/api/projects/${projectId.value}`)
    console.log('API响应状态:', response.status)
    console.log('API响应数据:', response.data)
    
    if (response.data) {
      // 直接使用响应数据填充表单
      const projectData = response.data
      
      // 逐个字段赋值，避免覆盖整个对象
      Object.keys(formData.value).forEach(key => {
        if (projectData[key] !== undefined) {
          formData.value[key] = projectData[key]
        }
      })
      
      console.log('表单数据填充完成:', formData.value)
      ElMessage.success('项目数据加载成功')
    } else {
      console.error('响应数据为空')
      ElMessage.error('获取项目详情失败：返回数据为空')
    }
  } catch (error) {
    console.error('获取项目详情失败:', error)
    if (error.response) {
      console.error('错误详情:', {
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data
      })
      ElMessage.error(`获取项目详情失败: ${error.response.status} ${error.response.statusText}`)
    } else if (error.request) {
      console.error('请求未收到响应:', error.request)
      ElMessage.error('网络错误，请检查服务器连接')
    } else {
      console.error('其他错误:', error.message)
      ElMessage.error('获取项目详情失败: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}
// 组件挂载时获取数据
onMounted(() => {
  if (isEditMode.value) {
    fetchProjectDetail()
  }
})

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchProjectDetail()
  }
})

const goBack = () => {
  router.go(-1)
}

const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    
    submitting.value = true

    let response
    if (!isEditMode.value) {
      // 新增项目
      response = await api.post(`/api/projects`, formData.value)
      ElMessage.success('项目添加成功')
    } else {
      // 编辑项目
      response = await api.put(`/api/projects/${projectId.value}`, formData.value)
      ElMessage.success('项目更新成功')
    }

    // 提交成功后返回列表页
    goBack()
    
  } catch (error) {
    console.error('操作失败:', error)
    if (error.response) {
      const errorMsg = error.response.data.message || error.response.data
      ElMessage.error(`操作失败: ${errorMsg}`)
    } else if (error.name === 'AxiosError') {
      ElMessage.error('网络错误，请检查连接')
    } else {
      ElMessage.error('请填写完整的项目信息')
    }
  } finally {
    submitting.value = false
  }
}


const industryOptions = ref([
  { value: '制造业', label: '制造业' },
  { value: '信息技术', label: '信息技术' },
  { value: '金融业', label: '金融业' },
  { value: '教育培训', label: '教育培训' },
  { value: '医疗健康', label: '医疗健康' },
  { value: '零售业', label: '零售业' },
  { value: '物流运输', label: '物流运输' },
  { value: '建筑工程', label: '建筑工程' },
  { value: '餐饮服务', label: '餐饮服务' },
  { value: '文化娱乐', label: '文化娱乐' },
  { value: '房地产', label: '房地产' },
  { value: '能源环保', label: '能源环保' },
  { value: '农业', label: '农业' },
  { value: '旅游酒店', label: '旅游酒店' },
  { value: '媒体广告', label: '媒体广告' },
  { value: '咨询服务', label: '咨询服务' },
  { value: '其他行业', label: '其他行业' }
])

const statusOptions = ref([
  { value: '在谈', label: '在谈' },
  { value: '已签约', label: '已签约' },
  { value: '建设中', label: '建设中' },
  { value: '竣工验收', label: '竣工验收' },
  { value: '审核中', label: '审核中' }
])

// 完整的验证规则
const rules = ref({
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  projectCode: [
    { required: true, message: '请输入项目编号', trigger: 'blur' }
  ],
  investor: [
    { required: true, message: '请输入投资方', trigger: 'blur' }
  ],
  industryCategory: [
    { required: true, message: '请选择产业类别', trigger: 'change' }
  ],
  projectType: [
    { required: true, message: '请选择项目类型', trigger: 'change' }
  ],
  state: [
    { required: true, message: '请选择项目阶段', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入项目简介', trigger: 'blur' }
  ],
  totalInvestment: [
    { required: true, message: '请输入计划总投资', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})
</script>

<style scoped>
.project-edit-container {
  padding: 20px;
}

.edit-form-card {
  margin-top: 20px;
}

.full-width {
  width: 100%;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.el-divider {
  margin: 30px 0;
}
</style>